package com.free.bsf.eureka.client.limitrate.provider;

import com.free.bsf.core.base.LimitRateException;
import com.free.bsf.core.util.ContextUtils;
import com.free.bsf.core.util.ConvertUtils;
import com.free.bsf.eureka.client.limitrate.LimitRateConfig;
import com.free.bsf.eureka.client.limitrate.LimitRateMonitor;
import lombok.val;
import redis.clients.jedis.JedisCluster;

import java.util.Arrays;

public class RedisProvider extends BaseProvider
{
    @Override
    public boolean add(String key, LimitRateConfig config){
        val redis = ContextUtils.getBean(JedisCluster.class,false);
        if(redis==null){
            throw new LimitRateException("未配置redis");
        }
        return LimitRateMonitor.hook("redis").run(key,()-> {
            val result = redis.eval(lua, Arrays.asList(key), Arrays.asList(config.getPeriod() + ""));
            val counter = ConvertUtils.tryConvert(result, Long.class);
            if (counter > config.getMax()) {
                return false;
            }
            return true;
        });
    }
    private static String lua=
            "local counter = redis.call(\"INCRBY\", KEYS[1], 1)\n" +
            "if counter == 1 then\n" +
            "redis.call(\"EXPIRE\", KEYS[1], ARGV[1])\n" +
            "end\n" +
            "return counter";
}
